<?php
	include 'connection.php';
	include 'header.php';
	
	function getEventViaCategory($link, $id) {
		$query 	= "SELECT * FROM event WHERE category = ".$id;
		$result = mysql_query($query, $link);
		
		if(mysql_num_rows($result) > 0) {
			$response = array();
			$idx = 0;
			while($row = mysql_fetch_array($result)) {
				$response[$idx] = $row;
				$idx++;
			}
			
			$response['length'] = $idx;
			return json_encode($response);
			
		} else {
			return json_encode(array('status'=>'empty'));
		}
	}
	
	function getEventViaID($link, $id) {
		$query 	= "SELECT * FROM event WHERE event_id = ".$id;
		$result = mysql_query($query, $link);
		
		if(mysql_num_rows($result) > 0) {
			$row 	= mysql_fetch_array($result);
			$row8	= array_map('utf8_encode', $row);
			return json_encode($row8);
		} else {
			return json_encode(array('status'=>'empty'));
		}
	}
	
	function searchEventByTitle($link, $id) {
		if ($id == "") {
			return json_encode(array('status'=>'input kosong'));
		} else {
			$query 	= "SELECT * FROM event WHERE title LIKE '%".$id."%'";
			$result = mysql_query($query, $link);
			
			if(mysql_num_rows($result) > 0) {
				$response = array();
				$idx = 0;
				while($row = mysql_fetch_array($result)) {
					$response[$idx] = $row;
					$idx++;
				}
				
				$response['length'] = $idx;
				return json_encode($response);
				
			} else {
				return json_encode(array('status'=>'empty'));
			}		
		}
	}
	
	function getAllEvent($link) {
		$query 	= "SELECT * FROM event";
		$result = mysql_query($query, $link);
		
		if(mysql_num_rows($result) > 0) {
			$response = array();
			$idx = 0;
			while($row = mysql_fetch_array($result)) {
				$response[$idx] = $row;
				$idx++;
			}
			$response['length'] = $idx;
			return json_encode($response);
		} else {
			return json_encode(array('status'=>'empty'));
		}		
	}
	
	if(isset($_GET["cata"])) {
		echo getEventViaCategory($link, $_GET["cata"]);
	} else if(isset($_GET["id"])) {
		if ($_GET["id"] == "all") {
			echo getAllEvent($link);
		} else {
			echo getEventViaID($link, $_GET["id"]);
		}
	} else if (isset($_GET["title"])) {
		echo searchEventByTitle($link, $_GET["title"]);
	}
?>